<template>
  <div>
    <treeselect v-model="selectItemName" :options="sysBmTypeOptions" :normalizer="normalizer"
                @select="select" placeholder="选择编码"/>
  </div>
</template>

<script>
import treeselect from "@riophae/vue-treeselect";
import {listSysBmType} from "@/api/system/sysBmType.js"

export default {
  name: "BmGenSelect",
  components: {
    treeselect
  },
  data() {
    return {
      code: '',
      resultCode:'',
      selectItemName:null,
      resultItem:null,
      sysBmTypeOptions: []
    }
  },
  created() {
    this.getTreeselect()
  },
  methods: {
    getTreeselect() {
      listSysBmType().then(response => {
        this.sysBmTypeOptions = [];
        // const data = {bmId: 0, name: '顶级节点', children: []};
        // data.children = this.handleTree(response.data, "bmId", "parentId");
        this.sysBmTypeOptions = this.handleTree(response.data, "bmId", "parentId");
      });
    },
    genCode(node) {
      let parent=''
      if (!this.isEmpty(node)){
        parent=node.parentId
      }
      if ((parent==''||parent=='0'||parent==0)&&this.code!='')return;
      this.code+=`${node.value}-`
      this.treeFindById(this.sysBmTypeOptions,parent)
      this.genCode(this.resultItem)
    },
    select(node) {
      this.selectItem=node
      // if (node.parentId==''||node.parentId==0||node.parentId=='0'){
      //   this.resultCode=node.value
      // }else {
      //   this.code=""
      //   this.genCode(node,node.parentId)
      //   this.code+=this.resultItem.value
      //   let strArr=this.code.split("-")
      //   strArr=strArr.reverse()
      //   let resultStr=strArr.toString().replaceAll(',','')
      //   this.resultCode=resultStr
      //   this.resultItem=null
      // }
      this.selectItem.sysBmId=node.bmId
      this.$emit("select",this.selectItem)
    },
    treeFindById(tree,bmId){
      if (this.isEmpty(tree))return
      tree.forEach(item=>{
        if (item.bmId==bmId){
          this.resultItem=item
          return
        }
        if (!this.isEmpty(item.children)){
          this.treeFindById(item.children,bmId)
        }
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.bmId,
        label: node.name,
        children: node.children
      };
    }

  }
}
</script>

<style scoped>

</style>
